package com.sicong.common.aop;

import com.sicong.common.enums.LogModuleEnum;
import com.sicong.common.annotation.Log;
import com.sicong.common.util.LogUtil;
import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationEventPublisher;

import java.util.Map;

@Aspect
@AllArgsConstructor
public class LogAspect {

    private final ApplicationEventPublisher publisher;

    @Around("@annotation(log)")
    public Object log(ProceedingJoinPoint point, Log log) {
        Object obj = null;
        try {
            obj = point.proceed();
            // 打印日志
            Map<String, Object> logInfo = LogUtil.getLogInfo(point);
            LogUtil.log((LogModuleEnum) logInfo.get("module"),
                    LogUtil.getIpAddress(),
                    (point.getTarget().getClass().getName() + "." + point.getSignature().getName() + "()"),
                    (String) logInfo.get("description"));
            publisher.publishEvent(log);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }
}
